package com.example.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.project.common.Result;
import com.example.project.entity.User;
import com.example.project.entity.Image;
import com.example.project.mapper.UserMapper;
import com.example.project.mapper.ImageMapper;
import com.example.project.service.UserService;
import com.example.project.dto.UpdatePasswordRequest;
import com.example.project.dto.UpdateProfileRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.time.LocalDateTime;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Value("${upload.path}")
    private String uploadPath;

    @Override
    public Result<?> getProfile(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 更新最后登录时间
        user.setLastLoginTime(LocalDateTime.now());
        userMapper.updateById(user);

        // 清除敏感信息
        user.setPassword(null);
        return Result.success(user);
    }

    @Override
    @Transactional
    public Result<?> updateProfile(Long userId, UpdateProfileRequest request) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 检查用户名是否已存在
        if (StringUtils.hasText(request.getUsername())) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, request.getUsername())
                    .ne(User::getId, userId);
            if (userMapper.selectOne(queryWrapper) != null) {
                return Result.error("用户名已存在");
            }
            user.setUsername(request.getUsername());
        }

        // 检查邮箱是否已存在
        if (StringUtils.hasText(request.getEmail())) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail, request.getEmail())
                    .ne(User::getId, userId);
            if (userMapper.selectOne(queryWrapper) != null) {
                return Result.error("邮箱已被使用");
            }
            user.setEmail(request.getEmail());
        }

        // 更新手机��
        if (StringUtils.hasText(request.getPhone())) {
            user.setPhone(request.getPhone());
        }

        userMapper.updateById(user);
        
        // 清除敏感信息
        user.setPassword(null);
        return Result.success(user);
    }

    @Override
    @Transactional
    public Result<?> updatePassword(Long userId, UpdatePasswordRequest request) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 验证旧密码
        if (!passwordEncoder.matches(request.getOldPassword(), user.getPassword())) {
            return Result.error("旧密码错误");
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(request.getNewPassword()));
        userMapper.updateById(user);
        
        return Result.success(null);
    }

    @Override
    @Transactional
    public Result<?> updateAvatar(Long userId, MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return Result.error("请选择要上传的头像");
        }

        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return Result.error("只能上传图片文件");
        }

        // 验证文件大小（5MB）
        if (file.getSize() > 5 * 1024 * 1024) {
            return Result.error("头像大小不能超过5MB");
        }

        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        try {
            // 删除旧头像
            if (user.getAvatarUrl() != null) {
                String oldAvatarUrl = user.getAvatarUrl();
                if (oldAvatarUrl.contains("/view/")) {
                    String imageId = oldAvatarUrl.substring(oldAvatarUrl.lastIndexOf("/") + 1);
                    try {
                        Long oldImageId = Long.parseLong(imageId);
                        Image oldImage = imageMapper.selectById(oldImageId);
                        if (oldImage != null) {
                            // 删除物理文件
                            File oldFile = new File(oldImage.getFilePath());
                            if (oldFile.exists()) {
                                oldFile.delete();
                            }
                            // 删除数据库记录
                            imageMapper.deleteById(oldImageId);
                        }
                    } catch (NumberFormatException e) {
                        log.warn("Invalid image id in avatar url: {}", oldAvatarUrl);
                    }
                }
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + extension;

            // 确保目录存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 保存文件
            File destFile = new File(uploadPath + File.separator + fileName);
            file.transferTo(destFile);

            // 保存图片信息
            Image image = new Image();
            image.setFileName(fileName);
            image.setFilePath(uploadPath + File.separator + fileName);
            image.setFileSize(file.getSize());
            image.setFileType(file.getContentType());
            image.setImageType(2); // 头像类型
            image.setUserId(userId);
            image.setStatus(1); // 设置状态为正常
            imageMapper.insert(image);

            // 更新用户头像URL
            user.setAvatarUrl("/api/image/view/" + image.getId());
            userMapper.updateById(user);

            return Result.success(user.getAvatarUrl());
        } catch (IOException e) {
            log.error("Upload avatar failed:", e);
            return Result.error("头像上传失败");
        }
    }

    // 添加工具方法
    private void validateImageFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("请选择要上传的头像");
        }

        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IllegalArgumentException("只能上传图片文件");
        }

        if (file.getSize() > 5 * 1024 * 1024) {
            throw new IllegalArgumentException("头像大小不能超过5MB");
        }
    }
} 
} 